﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Security.Cryptography;

namespace QRWin
{
    class HttpUtils
    {

        public static string GetCurrentDateTimeStr()
        {
            
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public static long GetCurrentDateTime()
        {
            long currentTicks = DateTime.Now.Ticks;
            DateTime dtFrom = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            long currentMillis = (currentTicks - dtFrom.Ticks) / 10000;
          //  return currentMillis;
            return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;
        }


        public static string getSign(string json,string appSecret)
        {
            json = json + "&appKey=" + appSecret;
            string md5Str=Md5(json); // md5
            //base64
            byte[] bytes = Encoding.UTF8.GetBytes(md5Str);
            return Convert.ToBase64String(bytes);


        }


        /// <summary>
        ///  32 bit md5
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Md5(string str)
        {
            var md5Csp = new MD5CryptoServiceProvider();
            byte[] md5Source = Encoding.UTF8.GetBytes(str);
            byte[] md5Out = md5Csp.ComputeHash(md5Source);
            string pwd = "";
            for (int i = 0; i < md5Out.Length; i++)
            {
                pwd += md5Out[i].ToString("x2");
            }
            return pwd;
        }


        public static void Get(string url)
        {

            string serviceAddress = url;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            Logger.WriteLog("HTTP RET STRING=" + retString);
            //  Console.WriteLine(retString);
            //  Console.ReadLine();
        }
    
        public static JObject Post(string url,string httpBody)
        {
            JObject jo = new JObject();
         
            try
            {

                string serviceAddress = url;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);

                request.Method = "POST";
                request.ContentType = "application/json";
                // string strContent = @"{ ""mmmm"": ""89e"",""nnnnnn"": ""0101943"",""kkkkkkk"": ""e8sodijf9""}";
                string strContent = httpBody;
                using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
                {
                    dataStream.Write(strContent);
                    dataStream.Close();
                }
           
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //if (response.StatusCode!= HttpStatusCode.OK)
                //{
                //    jo.Add("result", "2001");
                //    jo.Add("message", e.Message);
                //    jo.Add("push_time", GetCurrentDateTime());
                //}
                string encoding = response.ContentEncoding;
   
                if (encoding == null || encoding.Length < 1)
                {
                    encoding = "UTF-8"; //默认编码  
                }
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
                string retString = reader.ReadToEnd();

                Logger.WriteLog("HTTP RET STRING=" + retString);

                //解析josn
                 jo = JObject.Parse(retString);
            }
            catch (Exception e)
            {
                Logger.WriteLog("POST ERR=" + e.Message);
                Logger.WriteLog("POST URL=" + url);
                jo.Add("result", "2001");
                jo.Add("message", e.Message);
                jo.Add("push_time", GetCurrentDateTime());

            }
            return jo;

        } 


    }
}
